var db = function() { 'console' in window && console.log.call(console, arguments); };

//ebook render
var DoReader = {};
DoReader.opt = {
	lineNum : 30,
	lineHeight : 2,//em
	container : $('#readerbox'),
	nav : $("#sidebar .pager")
},
DoReader.pn = null,
DoReader.currpn = 1,
DoReader.currtype = 'v',
DoReader.utils = {
	isinpn : function (pos,pn){
		var _isinpn = true;
		var pnlines = DoReader.opt.lineNum;
		var _pn={};
		_pn.start = pnlines * pn;
		_pn.end = pnlines * (pn+1);
		
		if(pos.start >= _pn.end || pos.end <= _pn.start){
			_isinpn = false;
		}
		return _isinpn;
	},
	go2page : function(idx){
		$.scrollTo( '#item'+idx, 700);
		window.location.hash = 'pn'+idx;
		DoReader.currpn = idx;
		$("#sidebar .pager").trigger("updatepager", [idx]);
	},
	gethash : function(e){
		var el= $(e.target), href = el.attr('href');
	    if (!href) {
	      return;
	    }
	    hash = href.split('#')[1].toLowerCase();
		return hash;
	}
},
DoReader.render = function(html){
	//render first page get pagenum
	var _container = DoReader.opt.container,
		_nav = DoReader.opt.nav,
		_lineHeight = DoReader.opt.lineHeight,
		_lineNum = DoReader.opt.lineNum;
	
	$("#sidebar .pager").bind("updatepager", function(event, idx){
		$(this).find('a').removeClass('on');
		$(this).find('a').eq(idx-1).addClass('on');
		//db(idx);
	});
	var s = parseInt(_container.css('fontSize').replace('px',''));
	var html = html || '';
	if(html !== ''){
		_container.html('');
		var _html = [];
		_html.push('<div class="page-item" id="item'+ i +'">');
		_html.push('<div class="page-hd"></div><div class="page-bd"><div class="data">'+html+'</div></div>');
		_html.push('<div class="page-ft">' + i +'</div>');
		_html.push('</div>');
		$(_html.join('')).appendTo(_container);
	}
	var allHeight = _container.find('.data').innerHeight() / s;
	var perHeight = _lineHeight * _lineNum;
	DoReader.pn = Math.ceil(allHeight/perHeight);
	//db(DoReader.pn);
    //creat pages
	for (var i = 1 ; i <= DoReader.pn ; i++) {
		var _str = [];
		_str.push('<div class="page-item" id="item'+ i +'">');
		_str.push('<div class="page-hd"></div><div class="page-bd"><div class="data"></div></div>');
		_str.push('<div class="page-ft">' + i +'</div><div class="notation"></div>');
		_str.push('</div>');
		$(_str.join('')).appendTo(_container);
	}

    //get paragraph data
	var paragraph  = [];
	_container.find('.line').each(function(){
		var pos = {};
		var par_top = parseInt($(this).position().top);
		// a paragraph has attr margin-bottom eq line-height
		var par_btm = par_top + parseInt($(this).height());
		
		//the start line
		pos.start = par_top/(s * _lineHeight);
		//the end line
		pos.end = par_btm/(s * _lineHeight);
		paragraph.push(pos);
	});
	
	
	//get page's paragraph
	for(var j=0,len = paragraph.length;j<len;j++){
		paragraph[j]['pn'] = [];
		for(var i = 0 ; i < DoReader.pn ; i ++){
			var isin = DoReader.utils.isinpn(paragraph[j],i);
			if(isin){
				paragraph[j]['pn'].push(i+1);
			}
		}
	}
	//get paragraph's hidden lines
	for(var j=0,len = paragraph.length;j<len;j++){
		var pnlines = _lineNum;
		if(paragraph[j]['pn'].length === 2){
			var pn_endline = pnlines * (paragraph[j]['pn'][0]);
			var par_startline = paragraph[j].start;
			var hid_lines = pn_endline - par_startline;
			paragraph[j]['hidlines'] = hid_lines;
		}
	}
	
	//render all pages
	_container.find('.line').each(function(j){
		var __pn = paragraph[j]['pn'];
		$(this).clone().appendTo(_container.find('.data').eq(__pn[0]));
		if(paragraph[j]['pn'].length === 2){				
			$(this).clone().appendTo(_container.find('.data').eq(__pn[1]));
			$(_container.find('.data').get(__pn[1])).data('hidlines',paragraph[j]['hidlines']);
		}
	});
	//remove temp page
	$(_container.find('.page-item').get(0)).remove();
	
	//render hid lines
	_container.find('.data').each(function(i){
		if($(this).find('.line').get(0)){
			var _mt = parseInt($(this).data('hidlines')) * _lineHeight;
			if(!_mt) _mt = 0;
			
			$(this).find('.line').get(0).style.marginTop = '-'+ _mt +'em';
		}		
	});
	window.location.hash = 'pn1';	
},
DoReader.renderNav = function(){
	//db(DoReader.pn);
	var _pn = DoReader.pn;
	var _html = [];
	for(var i=0;i<_pn;i++){
		var j = i+1;
		var iscurrent = i === 0 ? 'on' : '';
		_html.push('<a class="topn '+iscurrent+'" href="#pn'+j+'">'+j+'</a>');
	}
	DoReader.opt.nav.html(_html.join(''));
},
DoReader.go2prev = function(){
	DoReader.currpn --;
	if(DoReader.currpn > 0){
		var _cssleft = 5+'em';
		DoReader.opt.container.find('.page-item').eq(DoReader.currpn-1).animate({left:_cssleft},600,function() {
			//$(window).scrollTop(0);
			$.scrollTo( 0, 600);
		});
		window.location.hash = 'pn'+DoReader.currpn;
		//db(DoReader.currpn);
	}else{
		DoReader.currpn = 1;
	}
	DoReader.updateToolsPn();
},
DoReader.go2next = function(){
	if(DoReader.currpn < DoReader.pn){
		var _cssleft = '-' + 48 + 'em';
		//db(DoReader.currpn-1);
		//db(DoReader.opt.container.find('.page-item').eq(DoReader.currpn-1).get(0));
		DoReader.opt.container.find('.page-item').eq(DoReader.currpn-1).animate({left:_cssleft},600,function() {
			$.scrollTo( 0, 600);
		});
		DoReader.currpn ++;
		window.location.hash = 'pn'+DoReader.currpn;
	}else{
		DoReader.currpn = DoReader.pn;
	}
	DoReader.updateToolsPn();
},
DoReader.go2prev2 = function(){
	DoReader.currpn --;
	if(DoReader.currpn > 0){
		DoReader.utils.go2page(DoReader.currpn);
	}else{
		DoReader.currpn = 1;
		return;
	}
};
DoReader.go2next2 = function(){
	DoReader.currpn ++;
	if(DoReader.currpn <= DoReader.pn){
		DoReader.utils.go2page(DoReader.currpn);
	}else{
		DoReader.currpn = DoReader.pn;
		return;
	}
};
DoReader.updateTools = function(){
	var posX = $('#readerbox').offset().left + $('#readerbox').outerWidth() + 2;
	$('#tools').css('left',posX+'px');
	var t = DoReader.currtype;
	if(t === 'v'){
		$('#tools').removeClass('tools-h').addClass('tools-v');
	}else{
		$('#tools').removeClass('tools-v').addClass('tools-h');
	}
};
DoReader.showTools = function(){
	var toolsTemp = $('#db-templ-tools').html();
	//db(toolsTemp);
	if($('#tools').get(0) !=='undefined');
		$(toolsTemp).appendTo($('#doc'));
	DoReader.updateTools();
	if($.browser.msie){
		$(window).bind('scroll',function(){
			var top = $(window).scrollTop()+100;
			var _lantency = null,_layTime = 60000;
			_lantency = setTimeout(function() {
				$('#tools').css('top',top+'px');
				$('#tools').find('.currpn').text(DoReader.currpn);
			}, _layTime);
		});
	}else{
		$('#tools').css({'top':'100px','position':'fixed'});
	}
	
	var showTools = function(e) { 
        $('#tools').stop().animate({ opacity: 1 });

        var _lantency = null,_layTime = 60000;
        _lantency = setTimeout(function() {
			$('#tools').stop().animate({ opacity: 0 });
		}, _layTime);
	};
	$(document).mousemove(showTools);
	$(document).click(showTools);
	
	$('#tools').find('.info').mouseenter(function(){
		$('#infotext').fadeIn(600);
	}).mouseleave(function(){
		$('#infotext').fadeOut(600);
	});
	
	$('#tools').find('.keycode').mouseenter(function(){
		$('#keytips').fadeIn(600);
	}).mouseleave(function(){
		$('#keytips').fadeOut(600);
	});	
	$('#tools').find('.up').click(function(e){
		alert(DoReader.currtype +'###'+DoReader.currpn);
		if (DoReader.currtype === 'v'){
			DoReader.go2prev2();
		}else{
			DoReader.go2prev();
		}
	});
	$('#tools').find('.down').click(function(e){
		alert(DoReader.currtype +'###'+DoReader.currpn);
		if (DoReader.currtype === 'v'){
			DoReader.go2next2();
		}else{
			DoReader.go2next();
		}
	});

};
DoReader.updateToolsPn = function(){
	$('#tools').find('.currpn').text(DoReader.currpn);
};
DoReader.showNotation = function(){
	DoReader.opt.container.find('.line').bind({
		mouseenter : function(e){
			$(this).find('.remark-point').show();
		},
		mouseleave : function(e){
			$(this).find('.remark-point').hide();
		}
	});
	var updateNote = function(data){
		var temp = '<div class="listitem">{con} - <a href="#">{author}</a></div>';
		var allnote = 50;
		var pernote = 5;
		var pager = allnote/pernote;
		var currpn = 2;
        var arr = [];
        for(var i in data){
        	if(i < 5){
				arr.push(temp.replace('{con}',data[i]['con']).replace('{author}',data[i]['author']).replace('{time}',data[i]['time']));
			}
		}
		$('#notelist').html(arr.join(''));
		
		var pagenav = [];
		pagenav.push('<div class="paginator"><span class="prev">&lt;前页</span>');
		for(var i = 1 ; i <= pager ; i++){
			if(i === currpn){
				pagenav.push('<span class="thispage">'+i+'</span>');
			}else{
				pagenav.push('<a href="#" rel="i">'+i+'</a>');
			}	
		}
		pagenav.push('<span class="next"><a href="#pn=4">后页&gt;</a> </span><span class="count">(共50个)</span></div>');

		$('#notepage').html(pagenav.join(''));
		
	};
	DoReader.opt.container.delegate('#noteform textarea','change',function(e){
		$('#noteform input').removeAttr("disabled");
	});
	DoReader.opt.container.delegate('#noteform','submit',function(e){
		alert(2);
		e.preventDefault();
		$.post('note.php', { content: $('#noteform textarea').val(), author: '2pm' }, function(data){
		    updateNote(data);
		    $('#noteform textarea').val('');
		    $('#noteform input').attr('disabled','disabled');
		},"json");
	});
	DoReader.opt.container.delegate('.paginator a','click',function(e){
		alert(1);
		e.preventDefault();
		var pn = $(this).attr('rel');
		$.ajax({  
		    type : 'GET',  
		    dataType : 'json',  
		    url : 'note.php?pn='+pn,  
		    success : function(data) {
		    	updateNote(data);
		    }		    
		});
	});
	$('.remark-point').bind('click',function(e){
		DoReader.opt.container.find('.notation').hide();
		var id = $(this).parents('.page-item').attr('id');
		$(this).parents('.line').wrap('<div>');
		var domstr = $(this).parents('.line').parent().html();
		var notationform = '<div class="noteform mod"><form id="noteform" action="note.php" method="post"><span class="close">关闭X</span><h2>添加批注<span>（<a href="#">全部50条</a>）</span></h2><div class="item"><textarea name="pa_note"></textarea></div><div class="btn"><div class="bn-flat"><input type="submit" value="发表" disabled="disabled"></div></div><div class="error"></div></form></div><div class="notelist"><div class="list" id="notelist"></div><div id="notepage"></div></div>';

		var posY = $(this).parents('.line').position().top + $('#'+id).find('.page-hd').outerHeight();
		var elpage = $('#'+id);
		DoReader.opt.container.find('.line').removeClass('noted');
		
		$(this).parents('.line').addClass('noted');
		elpage.find('.notation').html(domstr+notationform);
		elpage.find('.notation').css({'top': posY+'px'}).fadeIn(1);
		elpage.find('.notation .line').css('margin-top',0);
		elpage.find('.notation .close').click(function(e){
			$('.notation').fadeOut(1);
		});
		
		$.ajax({  
		    type : 'GET',  
		    dataType : 'json',  
		    url : 'note.php',  
		    success : function(data) {
		    	updateNote(data);
		    }		    
		});
		
	});
};
DoReader.closeNotation = function(){
	DoReader.opt.container.find('.notation').hide();
};
DoReader.evt = {
	evtKey : function(e){
		if(DoReader.currtype === 'h') {
			var c = (e.charCode) ? e.charCode : e.keyCode;
			switch (c){
				case 37: DoReader.go2prev();return false;//[<-]
				case 39: DoReader.go2next();return false;//[->]
				//case 38: go2prev();return false;//[^]
				//case 40: go2next();return false;//[V]
				case 75: DoReader.go2prev();return false;//[k]
				case 74: DoReader.go2next();return false;//[j]
				//default: alert(e.keyCode);
			}
		}
	},
	evtZoom : function(e){
		e.preventDefault();
		type = DoReader.utils.gethash(e);
		$('#container').get(0).className = type;
		$('#sidebar .zoom a').removeClass('on');
		$(this).addClass('on');
		DoReader.updateTools();
		DoReader.closeNotation();
	},
	evtSwType : function(e){
		e.preventDefault();
		DoReader.currpn = 1;
		var render_h = function(){
			var readerbox = $('#readerbox');
			var item = readerbox.find('.page-item');
			var pn = item.length;
			item.each(function(i){
				$(this).css('z-index',pn-i);
			});
			readerbox.removeClass('vertical').addClass('horizontal');
			readerbox.find('.page-item').css('left','5em');
			DoReader.currtype = 'h';
			$('.pagerbox').hide();
			$('.keydown').show();
			
			DoReader.updateTools();
		};
		var render_v = function(){
			var readerbox = $('#readerbox');
			readerbox.removeClass('horizontal').addClass('vertical');
			readerbox.find('.page-item').css({'z-index':1,'left':'0'});
			DoReader.currtype = 'v';
			$('.pagerbox').show();
			$('.keydown').hide();
			
			DoReader.updateTools();
		};
        $('#sidebar .type a').removeClass('on');
		$(this).addClass('on');
		
		var el= $(e.target), href = el.attr('href');
    	if (!href) {
          return;
        }
        hash = href.split('#')[1].toLowerCase();
        switch(hash){
        	case 'h' : render_h();return false;
        	case 'v' : render_v();return false;
        }
        DoReader.closeNotation();
	},
	evtScroll : function(){
		if(DoReader.currtype === 'v'){
			var scr_top = parseInt($(window).scrollTop() - $('#readerbox').offset().top);
			//db(scr_top);
			var el_page = $('#readerbox .page-item').get(0);
			var perH = $(el_page).outerHeight(true);
			var _pn = Math.floor(scr_top / perH);
			
			var _lantency = null,_layTime = 600;
			_lantency = setTimeout(function() {
				for(var i = 0 ; i < DoReader.pn ; i++){
					if (i == _pn) {
						var idx = i+1;
				  		window.location.hash = 'pn'+idx;
				  		DoReader.currpn = idx;
				  		DoReader.updateToolsPn();
					}
				}
			}, _layTime);
		}
	},
	evtPageNav : function(e){
        var hash = DoReader.utils.gethash(e);
        var idx = parseInt(hash.replace('pn',''))
        DoReader.utils.go2page(idx);
        //db(idx);
	},
	evtPageNav2 : function(e){
		var hash = DoReader.utils.gethash(e);
		switch (hash){
			case 'prev': DoReader.go2prev();return false;//[<-]
			case 'next': DoReader.go2next();return false;//[->]
		}
	}
};
function DoReaderInit(html){
	DoReader.render(html);
	var _lantency = null,_layTime = 1000;
	_lantency = setTimeout(function() {
		DoReader.renderNav();
		$('#sidebar .zoom a').click(DoReader.evt.evtZoom);
		$('#sidebar .type a').click(DoReader.evt.evtSwType);
		$('#sidebar .pager a').click(DoReader.evt.evtPageNav);
		$('#sidebar .keydown a').click(DoReader.evt.evtPageNav2);
		$(document).bind('keydown',DoReader.evt.evtKey);
		$(window).scroll(DoReader.evt.evtScroll);
		
		$('#container').find('sup').mouseenter(function(){
			var popinfo = $(this).attr('title');
			var offset = $(this).offset();
			var pos = {};
			pos.top = offset.top - 40;
			pos.left = offset.left + 20;
			$('#popinfo').text(popinfo).css({'position':'absolute','left':pos.left +'px','top':pos.top + 'px' }).show();
		}).mouseleave(function(){
			$('#popinfo').hide();
		});
		$('#container').find('a[rel=lightbox]').lightBox();
		DoReader.showTools();
		DoReader.showNotation();		
	}, _layTime);
}
function DoReaderPreview(html){
	DoReader.render(html);
	$('#sidebar .zoom a').click(DoReader.evt.evtZoom);
	$('#container').find('sup').mouseenter(function(){
		var popinfo = $(this).attr('title');
		var offset = $(this).offset();
		var pos = {};
		pos.top = offset.top - 40;
		pos.left = offset.left + 20;
		$('#popinfo').text(popinfo).css({'position':'absolute','left':pos.left +'px','top':pos.top + 'px' }).show();
	}).mouseleave(function(){
		$('#popinfo').hide();
	});
}

